import store from '@/store'
import { Message } from 'element-ui'
import tinymce from 'tinymce'
import { io } from 'socket.io-client'
import { sleep } from './helpers'
import { getInitPageList } from '@/utils/init'
import { getLocalPageList } from './save'

export default class Socket {
  constructor(options) {
    if (Socket.instance) return Socket.instance
    const { url, ...query } = options
    this.socket = io(url, { query, path: '/socket.io' })

    //监听服务器连接事件
    this.socket.on('connect', this.onConnect)
    //监听服务器关闭服务事件
    this.socket.on('disconnect', this.onDisconnect)
    //监听服务器端发送消息事件
    this.socket.on('doc_updated', this.onReceive)
    this.socket.on('connect_fail', this.onConnectFail)
    //鉴权消息事件
    this.socket.on('authorization_fail', this.onAuthFail)
    this.socket.on('doc_fail', this.onFail)
    Socket.instance = this
  }

  // 发送消息
  send(content, callback) {
    this.socket.emit('doc_update', { content }, (status, msg) => {
      if (status === 'success') {
        callback()
      } else {
        console.log('===onFail===', msg)
        Message.error(msg)
      }
    })
  }

  //断开连接
  disconnect() {
    this.socket.disconnect()
  }

  onConnect() {
    console.log('===onConnect===')
  }

  onDisconnect() {
    console.log('===onDisconnect===')
  }

  async onReceive(data) {
    console.log('===onReceive===')
    let jsonContent = {}
    try {
      jsonContent = JSON.parse(data)
      const remotePageList = getInitPageList(jsonContent)
      const localPageList = getLocalPageList()
      const editableIds = store.state.xmleditor.editableIds
      const remotePages = editableIds.map(id => remotePageList.find(i => i.pageId === id))
      const localPages = editableIds.map(id => localPageList.find(i => i.pageId === id))
      const compatRemotePages = remotePages.filter(i => i)
      const compatLocalPages = localPages.filter(i => i)
      if (!compatRemotePages.length || !compatLocalPages.length) {
        console.warn('editableIds异常')
        return
      }
      if (compatRemotePages.length !== compatLocalPages.length) {
        console.warn('查找对应页不一致')
        return
      }
      remotePages.forEach((_, index, arr) => {
        arr.splice(index, 1, localPages[index])
      })
      store.commit('xmleditor/INIT_EDITOR_DATA', { ...jsonContent, pageList: remotePageList })
      store.commit('xmleditor/UPDATE_DOC_STRUCTURE')
      store.commit('xmleditor/SET_PAGE_NONEDITABLE')
      tinymce.activeEditor.fire('pageUpdated')
    } catch (error) {
      return Message.error('文档数据错误')
    }
  }

  onConnectFail(msg) {
    Message.error(msg)
    console.log('===onConnectFail===', msg)
  }
  onAuthFail(msg) {
    console.log('===onAuthFail===', msg)
    Message.error(msg)
  }
  onFail(msg) {
    console.log('===onFail===', msg)
    Message.error(msg)
  }
}
